#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd $SCRIPT_DIR
source common_vars.sh

SUCCESS_DIR=/data/ndserver/statuslog
SUCCESS_LOG=$SUCCESS_DIR/file_backup.log
SHELL_PID_FILE=$SUCCESS_DIR/file_backup.pid
ERROR_DIR=/tmp/monitorbackup
ERROR_LOG=$ERROR_DIR/file_monitor.log
BACKUP_LIST_FILE=backup_list.conf
RETENTION_DAYS=7

[ ! -d $SUCCESS_DIR ] && mkdir -p $SUCCESS_DIR
[ ! -d $ERROR_DIR ] && mkdir -p $ERROR_DIR


function check_running(){
    if [ -f "$SHELL_PID_FILE" ];then
        SCRIPT=$(basename $0)
        SHELL_PID=$(cat $SHELL_PID_FILE)
        if ps -ef | awk '$2=="'$SHELL_PID'"' | grep -q $SCRIPT;then
            logging "another $SCRIPT process is running." $ERROR_LOG
            exit 1
        fi
    fi
    echo $$ > $SHELL_PID_FILE
    #echo "for test: sleep 10s for check_running, please open new session and run this script at the same time."
    #sleep 10
}

function upload_file(){
    if command -v python2.7 > /dev/null;then
        PYTHON=python2.7
    elif command -v python2.6 > /dev/null;then
        PYTHON=python2.6
    else
        logging "python check failure." $ERROR_LOG
        exit 1
    fi
    $PYTHON ../client/main.py -f $1 -t sysbak
}


function backup(){
    BACKUP_LIST=$(awk '
        /^\[/{
            if(a){print ""};a++;printf $0
        }
        /^--exclude=/{
            printf " "$0
        }
        END{
            print
        }' $BACKUP_LIST_FILE)

    echo "$BACKUP_LIST" | while read line
    do
        SRC_DIR=$(echo $line | awk '{print $1}' | sed -r 's#\[|/*\]##g')
        EXCLUDE_ARGS=$(echo $line | awk '{$1="";print}')
        if [ ! -d "$SRC_DIR" ];then
            logging "$SRC_DIR directory not exist." $ERROR_LOG
            continue
        fi
        SRC_NAME=$(echo $SRC_DIR | sed -r 's#^/|^/data/##g;s#/#_#g')
        BACKUP_DIR=$WEB_BACKUP_ROOT/$SRC_NAME/$FULLDATE1
        mkdir -p $BACKUP_DIR

        tar zcf $BACKUP_DIR/${SRC_NAME}_$FULLTIME1.tgz $EXCLUDE_ARGS $SRC_DIR
        if [ $? -eq 0 ];then
            logging "$SRC_DIR backup successful, $BACKUP_DIR/${SRC_NAME}_$FULLTIME1.tgz" $SUCCESS_LOG
        else
            logging "$SRC_DIR backup failed." $ERROR_LOG
            exit 1
        fi

        #upload_file $BACKUP_DIR/${SRC_NAME}_$FULLTIME1.tgz

        DELETE_BEFORE_DAY=$(date -d "$RETENTION_DAYS days ago" +%Y%m%d)
        DELETE_LIST=$(ls $WEB_BACKUP_ROOT/$SRC_NAME | awk '$0<="'$DELETE_BEFORE_DAY'"{print "'$WEB_BACKUP_ROOT/$SRC_NAME/'"$0}')
        if [ -n "$DELETE_LIST" ];then
            echo "the following expired directories will be deleted."
            echo "$DELETE_LIST"
        fi
    done
}


# main step
check_running
backup
rm -f $SHELL_PID_FILE